<template>
  <view class="bottom_cart">
    <view class="cart_content">
      <view class="cart" @click="open">
        <view class="c_icon"></view>
        <view class="c_num">{{ orderGoods.length }}</view>
      </view>
    </view>
    <view class="price_content">
      <view class="p_all">￥{{ all_money }}</view>
      <view class="p_son">配送费￥{{ p_money }}元</view>
    </view>
    <view class="computed" @click="go_settlement">去结算</view>
    <view :style="`height:${length}`" class="popup">
      <up-swipe-action>
        <up-swipe-action-item v-for="(item, index) in orderGoods" :key="item" v-model:show="item.showDelete"
          :options="options1" @click="deleteGoods(index)">
          <view class="swipe-action up-border-top up-border-bottom">
            <view class="swipe-action__content">
              <!-- <text class="swipe-action__content__text">基础使用</text> -->
              <view class="p_item">
                <view class="p_icon"><img :src="item.icon" alt="" /></view>
                <view class="p_right">
                  <view class="p_name">{{ item.name }}</view>
                  <view class="p_bottom">
                    <view class="p_price">
                      <view class="yuan">￥</view>
                      <view class="price">{{ item.price }}</view>
                    </view>
                    <view class="p_count">
                      <view class="p_sub" @click="subCount(index)"></view>
                      {{ item.count }}
                      <view class="p_add" @click="addCount(index)"></view>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </up-swipe-action-item>
      </up-swipe-action>
      <view v-if="orderGoods.length == 0" class="empty">
        <img src="@/assets/order/seller_love.svg" alt="" />
        快去挑选好吃的餐品吧~
      </view>
    </view>
    <!-- 消息提示框 -->
    <view>
      <up-toast ref="uToastRef" style="pointer-events: none;"></up-toast>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive } from "vue";
import { defineEmits } from "vue";
import { watch, watchEffect } from "vue";
import { saveOrder } from "@/api/order";
import useOrderStore from "@/store/modules/order";
import useUserStore from "@/store/modules/user";
import CryptoJS from "crypto-js";
let orderStore = useOrderStore();
let userStore = useUserStore();
const emit = defineEmits(["subCount", "addCount", "deleteGoods", "clearCart"]);
const show = ref(false);
const uToastRef = ref(null)
// 使用 reactive 创建响应式对象
const options1 = reactive([
  {
    text: "删除",
  },
]);
/**
 * 获取父组件传递的商品数据
 */
const props = defineProps({
  orderGoods: {
    required: true,
  },
});
/**
 * 打开关闭购物车的方法
 */
let length = ref(0);

// 定义方法打开购物车
function open() {
  if (length.value) {
    length.value = 0;
  } else {
    if (props.orderGoods.length == 0) {
      length.value = "200rpx";
      return;
    }
    if (props.orderGoods.length <= 3) {
      length.value = `${props.orderGoods.length + 2}00rpx`;
    } else {
      length.value = "500rpx";
    }
  }
}

/**
 * 添加数量和减少数量
 */
function addCount(index) {
  // console.log(props.orderGoods[0]);

  emit("addCount", index);
}

function subCount(index) {
  emit("subCount", index);
}

/**
 * 删除商品
 */
function deleteGoods(index) {
  emit("deleteGoods", index);
}
/**
 * 计算总价格和配送费
 */
let all_money = ref(0);
let p_money = ref(0);
watchEffect(() => {
  all_money.value = 0;
  p_money.value = 0;
  props.orderGoods.forEach((item) => {
    all_money.value += Number(item.price) * Number(item.count);
    // 配送费一个一块钱
    p_money.value += 1;
  });
  all_money.value = all_money.value.toFixed(2);
});

/**
 * 去结算
 */
async function go_settlement() {
  if (props.orderGoods.length == 0) {
    uToastRef.value.show({
      type: 'warning',
      message: "请先挑选满意的餐品吧~",
      duration: '1000',
    });
    return
  }
  // 将订单存储到数据库中
  let timestamp = Date.now(); //当前时间戳
  let groupedData = [];
  let totalMoney = 0;
  let totalCount = 0;
  groupedData = props.orderGoods.reduce((acc, item) => {
    const existingSeller = acc.find(
      (seller) => seller.sellerId === item.sellerId
    );
    // 单个商品的总价
    const itemTotalPrice = Number(item.price) * Number(item.count);
    if (existingSeller) {
      existingSeller.goods.push(item);
      existingSeller.allPrice = (Number(existingSeller.allPrice) + itemTotalPrice).toFixed(2);
      existingSeller.allCount = Number(existingSeller.allCount) + Number(item.count)
    } else {
      acc.push({
        userId: userStore.userId,
        sellerName: item.sellerName,
        sellerId: item.sellerId,
        allPrice: itemTotalPrice.toFixed(2),
        allCount: item.count,
        startTime: timestamp,
        orderId: generateOrderId(userStore.userId, item.sellerId, timestamp),
        goods: [item],
      });
    }
    return acc;
  }, []);

  // 计算整个订单总价和总件数
  groupedData.forEach(item => {
    totalMoney += Number(item.allPrice)
    totalCount += Number(item.allCount)
  });
  totalMoney = totalMoney.toFixed(2)


  // 保存订单
  saveOrder({
    userId: userStore.userId,
    startTime: groupedData[0].startTime,
    isPay: false,
    isSend: false,
    isReceive: false,
    isCancel: false,
    order: groupedData,
    totalMoney,
    totalCount
  })
    .then((res) => {
      if (res.code == 200) {
        // 将当前结算的订单id存储起来
        orderStore.addCurrentOrderId(res.orderId);
        uni.navigateTo({ url: "/pages/components/order/settlement" });
        // 清空购物车
        emit('clearCart')
        length.value = 0;
      } else {
        console.log(失败);
      }
    })
    .catch((err) => {
      uToastRef.value.show({
        type: 'error',
        message: "网络开了点小差~",
        duration: '1000',
      });
      console.log(失败);
    });

}

/**
 * 生成唯一订单id的方法
 */
function generateOrderId(buyerId, sellerId, timestamp) {
  //TODO: 需要判断 buyerId, sellerId, timestamp都不能为空
  // 将买家ID、卖家ID和时间戳拼接成一个字符串
  const rawData = `${buyerId}-${sellerId}-${timestamp}`;
  const hash = CryptoJS.MD5(rawData).toString();
  // 将哈希值转换为纯数字
  let numericHash = "";
  for (let i = 0; i < hash.length; i++) {
    const charCode = hash.charCodeAt(i);
    numericHash += charCode.toString();
  }

  // 截取前12位数字
  const orderId = numericHash.slice(0, 12);
  return orderId;
}
</script>

<style lang="scss" scoped>
.bottom_cart {
  width: 100%;
  height: 100rpx;
  background-color: #000000;
  display: flex;
  position: absolute;
  bottom: 0;
  left: 0;
  z-index: 10;

  .cart_content {
    width: 120rpx;
    height: 120rpx;
    border-radius: 50%;
    margin: 0 20rpx;
    background-color: #000000;
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    bottom: 0;
    z-index: 10;

    .cart {
      width: 95rpx;
      height: 95rpx;
      border-radius: 50%;
      border: #000000;
      background-color: #26b53e;
      display: flex;
      justify-content: center;
      align-items: center;
      z-index: 10;
      z-index: 10;

      .c_icon {
        width: 50rpx;
        height: 50rpx;
        background-image: url("@/assets/order/cart.svg");
        background-size: cover;
      }

      .c_num {
        width: 30rpx;
        height: 30rpx;
        background-color: #ec1c24;
        color: white;
        font-size: 24rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 50%;
        position: absolute;
        top: 10rpx;
        right: 10rpx;
      }
    }
  }

  .price_content {
    height: 100%;
    flex: 1;
    color: white;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    padding: 0 0 0 160rpx;

    .p_all {
      font-size: 32rpx;
      font-weight: 600;
    }

    .p_son {
      font-size: 24rpx;
      color: $uni-text-color-grey;
    }
  }

  .computed {
    width: 200rpx;
    height: 100%;
    display: flex;
    background-color: #26b53e;
    justify-content: center;
    align-items: center;
    font-weight: 600;
    color: white;
    position: absolute;
    bottom: 0;
    right: 0;
  }

  // .cart_popup {
  //   :deep(.u-popup__content) {
  //     height: 100px;
  //     position: fixed;
  //     bottom: 100px;
  //     right: 0;
  //     left: 0;
  //     z-index: 8 !important;
  //   }
  // }
  .popup {
    width: 100%;
    height: 0;
    background-color: white;
    transition: all 0.2s;
    position: absolute;
    bottom: 100%;
    box-shadow: 0 0 30rpx 20rpx rgba(180, 180, 180, 0.2);
    border-radius: 20rpx 20px 0 0;
    overflow: auto;

    .empty {
      display: flex;
      flex-direction: column;
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      color: $uni-text-color-grey;
      align-items: center;

      img {
        width: 120rpx;
        height: 120rpx;
        margin-bottom: 20rpx;
      }
    }
  }

  .p_item {
    width: 100%;
    height: 160rpx;
    display: flex;
    padding: 20rpx;
    border-bottom: 2rpx solid #eeeeee;

    .p_icon {
      width: 120rpx;
      height: 100%;

      img {
        width: 120rpx;
        height: 100%;
        border-radius: 20rpx;
      }
    }

    .p_right {
      flex: 1;
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      padding: 0 30rpx;

      .p_name {
        font-size: 28rpx;
        font-weight: 600;
      }

      .p_bottom {
        width: 100%;
        display: flex;
        justify-content: space-between;

        .p_price {
          display: flex;
          align-items: center;

          .yuan {
            font-size: 20rpx;
            color: #ec1c24;
          }

          .price {
            font-size: 28rpx;
          }
        }

        .p_count {
          display: flex;
          align-items: center;
          justify-content: space-between;
          width: 160rpx;

          .p_sub,
          .p_add {
            width: 40rpx;
            height: 40rpx;
          }

          .p_sub {
            background-image: url("@/assets/order/count_sub.svg");
            background-size: cover;
          }

          .p_add {
            background-image: url("@/assets/order/count_add.svg");
            background-size: cover;
          }
        }
      }
    }
  }
}
</style>